package com.fitzone.web.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fitzone.common.exception.BaseException;
import com.fitzone.common.exception.OrderBusinessException;
import com.fitzone.common.utils.HttpClientUtil;
import com.fitzone.model.dto.StoreDTO;
import com.fitzone.model.dto.StoreMiniDTO;
import com.fitzone.model.entity.Banner;
import com.fitzone.model.entity.Store;
import com.fitzone.model.vo.StoreMiniVO;
import com.fitzone.model.vo.StoreNameMiniVO;
import com.fitzone.model.vo.StoreVO;
import com.fitzone.web.mapper.BannerMapper;
import com.fitzone.web.mapper.StoreMapper;
import com.fitzone.web.service.BannerService;
import com.fitzone.web.service.StoreService;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.*;

@Service
public class StoreServiceImpl extends ServiceImpl<StoreMapper, Store> implements StoreService {
    @Autowired
    private BannerService bannerService;
    @Autowired
    private StoreMapper storeMapper;
    @Autowired
    private BannerMapper bannerMapper;

    private static final String baiduMapBaseUrl = "https://api.map.baidu.com/geocoding/v3/";
    private static final String ak = "3ULfoSSLXeHLai20j2GMGACbDhR91jC0";

    /**
     * 添加门店
     * @param storeDTO
     */
    @Override
    public void saveStore(StoreDTO storeDTO) {
        Store store = new Store();
        BeanUtils.copyProperties(storeDTO, store);

        // 保存banner
        if (storeDTO.getBanner() != null) {
            for (Banner banner : storeDTO.getBanner()) {
                banner.setStoreId(store.getId());
                bannerService.save(banner);
            }
        }

        try {
            // 使用try-with-resources确保httpClient正确关闭
            try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
                String requestUrl = baiduMapBaseUrl + "?address=" +
                        URLEncoder.encode(storeDTO.getAddress(), "UTF-8") + "&output=json&ak=" + ak;
                HttpGet httpGet = new HttpGet(requestUrl);

                try (CloseableHttpResponse response = httpClient.execute(httpGet)) {
                    HttpEntity entity = response.getEntity();
                    String shopCoordinate = EntityUtils.toString(entity);
                    JSONObject jsonObject = JSON.parseObject(shopCoordinate);
                    if (!"0".equals(jsonObject.getString("status"))) {
                        throw new OrderBusinessException("店铺地址解析失败");
                    }
                    // 数据解析
                    JSONObject location = jsonObject.getJSONObject("result").getJSONObject("location");
                    String lat = location.getString("lat");
                    String lng = location.getString("lng");
                    System.out.println("lng = " + lng);
                    System.out.println("lat = " + lat);
                    store.setLatitude(lat);
                    store.setLongitude(lng);
                } catch (IOException e) {
                    // 如果请求失败，则记录异常并抛出，由上层处理
                    throw new RuntimeException("Error fetching coordinates for store", e);
                }
            } catch (IOException e) {
                // 如果httpClient创建失败，记录异常并抛出，由上层处理
                throw new RuntimeException("Error creating HTTP client", e);
            }
            // 保存店铺信息，如果前面的HTTP请求成功的话
            this.save(store);
        } catch (Exception e) {
            // 通用的异常处理逻辑（如果需要的话）
            e.printStackTrace();
        }
    }

    /**
     * 修改门店
     * @param storeDTO
     */
    @Override
    public void updateStore(StoreDTO storeDTO) {
        Store store = new Store();
        BeanUtils.copyProperties(storeDTO,store);

        // 删除banner
        LambdaQueryWrapper<Banner> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Banner::getStoreId, store.getId());
        bannerService.remove(queryWrapper);

        // 保存banner
        if (storeDTO.getBanner() != null && storeDTO.getBanner().size() > 0) {
            for (Banner banner : storeDTO.getBanner()) {
                banner.setStoreId(store.getId());
                bannerService.updateById(banner);
            }
        }
        try {
            // 使用try-with-resources确保httpClient正确关闭
            try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
                String requestUrl = baiduMapBaseUrl + "?address=" +
                        URLEncoder.encode(storeDTO.getAddress(), "UTF-8") + "&output=json&ak=" + ak;
                HttpGet httpGet = new HttpGet(requestUrl);

                try (CloseableHttpResponse response = httpClient.execute(httpGet)) {
                    HttpEntity entity = response.getEntity();
                    String shopCoordinate = EntityUtils.toString(entity);
                    JSONObject jsonObject = JSON.parseObject(shopCoordinate);
                    if (!"0".equals(jsonObject.getString("status"))) {
                        throw new BaseException("店铺地址解析失败");
                    }
                    // 数据解析
                    JSONObject location = jsonObject.getJSONObject("result").getJSONObject("location");
                    String lat = location.getString("lat");
                    String lng = location.getString("lng");
                    System.out.println("lng = " + lng);
                    System.out.println("lat = " + lat);
                    store.setLatitude(lat);
                    store.setLongitude(lng);
                } catch (IOException e) {
                    // 如果请求失败，则记录异常并抛出，由上层处理
                    throw new RuntimeException("Error fetching coordinates for store", e);
                }
            } catch (IOException e) {
                // 如果httpClient创建失败，记录异常并抛出，由上层处理
                throw new RuntimeException("Error creating HTTP client", e);
            }
            // 保存店铺信息，如果前面的HTTP请求成功的话
            this.updateById(store);
        } catch (Exception e) {
            // 通用的异常处理逻辑（如果需要的话）
            e.printStackTrace();
        }
    }

    /**
     * 根据id来查询门店详情
     * @param id
     * @return
     */
    @Override
    public StoreVO miniStoreDetail(Long id) {
        LambdaQueryWrapper<Store> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Store::getId,id);
        List<Store> stores = storeMapper.selectList(queryWrapper);
        StoreVO storeVO = new StoreVO();
        for (Store store : stores) {
            BeanUtils.copyProperties(store,storeVO);
            LambdaQueryWrapper<Banner> bannerQueryWrapper = new LambdaQueryWrapper<>();
            bannerQueryWrapper.eq(Banner::getStoreId,store.getId());
            List<Banner> banners = bannerService.list(bannerQueryWrapper);
            storeVO.setBanner(banners);
        }
        return storeVO;
    }

    /**
     * 门店列表
     * @param storeMiniDTO
     * @return
     */
    @Override
    public List<StoreMiniVO> miniStoreList(StoreMiniDTO storeMiniDTO) {
        LambdaQueryWrapper<Store> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(storeMiniDTO.getCity() != null,Store::getCity,storeMiniDTO.getCity())
                .eq(storeMiniDTO.getLabel() != null,Store::getLabel,storeMiniDTO.getLabel());
        List<Store> stores = storeMapper.selectList(queryWrapper);
        ArrayList<StoreMiniVO> list = new ArrayList<>();
        for (Store store : stores) {
            StoreMiniVO storeMiniVO = new StoreMiniVO();
            BeanUtils.copyProperties(store,storeMiniVO);
            list.add(storeMiniVO);
        }
        return list;
    }

    @Override
    public List<StoreNameMiniVO> getCity() {
        LambdaQueryWrapper<Store> queryWrapper = new LambdaQueryWrapper<>();
        List<Store> stores = storeMapper.selectList(queryWrapper);
        HashSet<String> uniqueCities = new HashSet<>();
        ArrayList<StoreNameMiniVO> list = new ArrayList<>();

        for (Store store : stores) {
            String city = store.getCity();

            // 如果城市已经存在于HashSet中，跳过当前循环，继续处理下一个城市
            if (uniqueCities.contains(city)) {
                continue;
            }

            uniqueCities.add(city);

            StoreNameMiniVO storeNameMiniVO = new StoreNameMiniVO();
            storeNameMiniVO.setCity(city);
            list.add(storeNameMiniVO);
        }

        return list;
    }

    @Override
    public List<StoreMiniVO> getCityStore(String city) {
        LambdaQueryWrapper<Store> queryWrapper =  new LambdaQueryWrapper<>();
        queryWrapper.like(city != null,Store::getCity,city);

        List<Store> stores = storeMapper.selectList(queryWrapper);

        ArrayList<StoreMiniVO> list = new ArrayList<>();

        for (Store store : stores) {
            StoreMiniVO storeMiniVO = new StoreMiniVO();
            BeanUtils.copyProperties(store,storeMiniVO);
            list.add(storeMiniVO);
        }
        return list;
    }

}
